import React, { Component } from 'react'
import Child from '../Child'
import './index.css'

class Parent extends Component {
  state = {
    list: [
      {
        id: 1,
        name: '超级好吃的棒棒糖',
        price: 18.8,
        info: '开业大酬宾，全场8折',
      },
      {
        id: 2,
        name: '超级好吃的大鸡腿',
        price: 34.2,
        info: '开业大酬宾，全场8折',
      },
      {
        id: 3,
        name: '超级无敌的冰激凌',
        price: 14.2,
        info: '开业大酬宾，全场8折',
      },
    ],
  }
  // 1. 父组件准备函数并传递给子组件
  changePrice = (id, price) => {
    // 3. 父组件在回调函数中通过形参接收传递过来的数据并做相应操作
    this.setState({
      list: this.state.list.map((item) => {
        if (item.id === id) {
          let p = item.price - price
          p = +p.toFixed(2) // toFixed 返回的是一个字符串
          if (p < 0) p = 0
          return {
            ...item,
            price: p,
          }
        } else {
          return item
        }
      }),
    })
  }
  render() {
    const { list } = this.state
    return (
      <div className='parent'>
        {list.map((item) => (
          <Child key={item.id} {...item} changePrice={this.changePrice} />
        ))}
      </div>
    )
  }
}

export default Parent
